package com.ititer.dao.impl;

import static com.ititer.util.MyBatisCriteriaFactory.newCriteria;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import com.ititer.dao.AccountDao;
import com.ititer.mapper.AccountMapper;
import com.ititer.model.Account;
import com.ititer.model.AccountCriteria;

@Repository
public class AccountDaoImpl implements AccountDao {
	@Autowired
	private AccountMapper accountMapper;

	@Override
	public int create(Account account) {
		return accountMapper.insert(account);
	}

	@Override
	public int update(Account account) {
		return accountMapper.updateByPrimaryKey(account);
	}

	@Override
	public boolean isEmailExist(String email) {
		AccountCriteria example = newCriteria(AccountCriteria.class);
		example.createCriteria().andEmailEqualTo(email);
		List<Account> accounts = accountMapper.selectByExample(example);
		if (CollectionUtils.isEmpty(accounts)) {
			return false;
		}
		return true;
	}

	@Override
	public Account getAccount(String email, String password) {
		AccountCriteria example = newCriteria(AccountCriteria.class);
		example.createCriteria().andEmailEqualTo(email).andPasswdEqualTo(password);
		List<Account> accounts = accountMapper.selectByExample(example);
		if (accounts == null) {
			return null;
		}
		return accounts.get(0);
	}

	@Override
	public boolean isUriExist(String uri) {
		AccountCriteria example = newCriteria(AccountCriteria.class);
		example.createCriteria().andUriEqualTo(uri);

		int count = accountMapper.countByExample(example);
		if (count > 0) {
			return true;
		}
		return false;
	}

	@Override
	public Account getByUri(String uri) {
		AccountCriteria example = newCriteria(AccountCriteria.class);
		example.createCriteria().andUriEqualTo(uri);
		List<Account> accounts = accountMapper.selectByExample(example);
		if (CollectionUtils.isEmpty(accounts)) {
			return null;
		}
		return accounts.get(0);
	}

}
